package com.yequan.hbb.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.yequan.hbb.customview.ConerImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

class CornerImageTask extends AsyncTask<String, Void, Bitmap> {
    private ConerImageView img;
    private String url;
    private int id;
    public CornerImageTask(ConerImageView img, int id) {
        this.img = img;
        img.setTag(this);
        this.id = id;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
       // img.setImageResource(id);
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        try {
            url = params[0];
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            int code = connection.getResponseCode();
            if (code == 200) {
                return BitmapFactory.decodeStream(connection.getInputStream());
            }
        } catch (IOException ignored) {
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (bitmap != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            // InputStream isBm = new ByteArrayInputStream(baos.toByteArray());
            bitmap = PicScaleUtils.decodeBitmap(img.getWidth(), img.getHeight(), baos.toByteArray());
            img.setBitmap(bitmap);
            ImageUtils.cache.put(url, bitmap);
        } else {
        //    img.setBitmap(img.getContext().getResources().);
        }
    }

    @Override
    protected void onCancelled(Bitmap bitmap) {
        if (bitmap != null) {
            CornerImageUtils.cache.put(url, bitmap);
        }
    }
}
